package com.leyou.item.controller;

import com.leyou.common.utils.PageResult;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pojo.Brand;

import java.util.List;

/**
 * Author: Saka
 * Date: 2019/1/15
 * Time: 20:57
 */
@RestController
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     *
     * 查询品牌
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows,
            @RequestParam(value = "sortBy",required = false)String sortBy,
            @RequestParam(value = "desc",defaultValue = "false")Boolean desc,
            @RequestParam(value = "key",required = false)String key
    ) {

        PageResult<Brand> result = this.brandService.queryBrandByPageAndSort(page, rows, sortBy, desc, key);
        if (result != null && 0!=result.getItems().size()) {
            return ResponseEntity.ok(result);

        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();

    }

    /**
     * 新增品牌
     * @param brand
     * @param cids
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand,@RequestParam("cids")List<Long> cids) {

        this.brandService.saveBrand(brand, cids);
        //返回201
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }

    @PutMapping
    public ResponseEntity<Void> updataBrand(Brand brand,@RequestParam("cids")List<Long> cids) {

        this.brandService.updataBrand(brand, cids);
        //返回201
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }

    /**
     * 删除商品
     *
     */
    @DeleteMapping("bid/{bid}")
    public ResponseEntity<Void> deleteByBrandId(@PathVariable("bid")Long bid) {
        try {
            this.brandService.deleteByBrandId(bid);
            this.brandService.deleteByCategoryBrandId(bid);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();


    }

    /**
     *
     *根据分类查询商品信息
     * @param cid
     * @return
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandByCategory(@PathVariable("cid") Long cid) {
        List<Brand> list = this.brandService.queryBrandByCategory(cid);
        if (list != null && 0!=list.size()) {
            return ResponseEntity.ok(list);

        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();

    }

}
